<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="500px"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getUnitCategory, addUnitCategory, updateUnitCategory } from '/@/api/ehs/unitCategory';
  import { addOrUpdateUnitCategorySchema } from './unitCategory.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { queryEnumOptions } from '/@/api/platform/enum';
  const { createMessage } = useMessage();
  import { queryUnitCategory } from '/@/api/ehs/unitCategory';
  import { queryDangerDb } from '/@/api/ehs/templateHazard';
  export default defineComponent({
    name: 'AddOrUpdateUnitCategory',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 130,
        schemas: addOrUpdateUnitCategorySchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
        }
        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });
        getUnitCategoryTreeList();
        queryEnumOptions('EhsUnitTypeEnum').then((res) => {
          // console.log('option res', res);
          if (res != undefined && res != null && res.length > 0x0) {
            let tmp = res[0].options.map((option) => {
              return {
                value: option.key,
                label: option.value,
              };
            });
            updateSchema({
              field: 'uctype',
              componentProps: {
                options: tmp,
              },
            });
          }
        });
        queryDangerDb({ keytype: 0 }).then((res) => {
          updateSchema({
            field: 'hdbcd',
            componentProps: {
              options: res,
              fieldNames: { label: 'hdbnm', value: 'hdbcd' },
            },
          });
          if (operateType.value == OperationTypeEnum.ADD) {
            setFieldsValue({
              hdbcd: res[0].hdbcd,
            });
          }
        });
        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (operateType.value == OperationTypeEnum.EDIT) {
          getUnitCategoryById();
          updateSchema({
            field: 'uccd',
            componentProps: { disabled: true },
          });
        } else {
          updateSchema({
            field: 'uccd',
            componentProps: { disabled: false },
          });
        }
      });

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      async function getUnitCategoryById() {
        getUnitCategory(dataId.value)
          .then((res) => {
            console.log('res', res);
            setFieldsValue({
              ...res,
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addUnitCategory({ ...values })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateUnitCategory({ ...values })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
              // createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }
      function getUnitCategoryTreeList() {
        queryUnitCategory()
          .then((res) => {
            //父级单元分类选项集合
            updateSchema({
              field: 'puccd',
              componentProps: {
                treeData: operateType.value == OperationTypeEnum.EDIT ? deepFilter(res) : res,
                fieldNames: { label: 'ucnm', value: 'uccd', children: 'children' },
              },
            });
          })
          .catch((e) => {
            console.log('catch ', e);
          });
      }
      // 过滤分类菜单,不让选自己以及自己的子级分类作为上级菜单
      function deepFilter(arr) {
        return arr.filter((item) => {
          if (item.children) item.children = deepFilter(item.children);
          return item.uccd != dataId.value;
        });
      }
      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      onMounted(() => {});
      return {
        operateType,
        displayModuleTitle,
        registerModal,
        registerForm,
        getUnitCategoryById,
        onButtonOkClick,
        opSuccess,
        getUnitCategoryTreeList,
      };
    },
  });
</script>

<style scoped></style>
